package com.youfang.sixthmedia.net;

import java.util.Arrays;
import java.util.List;

import org.json.JSONObject;

/**
 * 对所有发往服务器的 请求 的抽象
 * 
 * @author teddy
 * 
 */
public abstract class Request implements Message {
	protected final String TAG = this.getClass().getSimpleName();

	// 键值对模式
	public static final int MODE_KEY_VALUE = 1;

	// 纯粹的POST
	public static final int MODE_PURE_JSON = 2;

	protected int mode = MODE_KEY_VALUE;

	// 该业务请求是必须需要服务端有返回的（也就是服务端不能出现服务端点url不存在的情况：如http的404）
	protected boolean serverEndPointMandatory = true;

	protected int type = TYPE_YOUFANG;
	protected String actionPath = "/soufang/public/index.php";// action的路径
	protected int method = Message.METHOD_GET;

	public Request() {
		this.genMetaData();
	}

	public boolean isServerEndPointMandatory() {
		return serverEndPointMandatory;
	}

	protected void setServerEndPointMandatory(boolean serverEndPointMandatory) {
		this.serverEndPointMandatory = serverEndPointMandatory;
	}

	// 子类提供传送的参数
	public abstract List<Pair> getParams();

	// 子类在该方法中注册消息类型与action的路径
	public abstract void genMetaData();

	public JSONObject getPureJSON() throws Exception {
		return null;
	}

	// 在组合成请求路径时增加前缀
	public String getActionPath() {
		return this.actionPath;
	}

	protected void setActionPath(String actionPath) {
		this.actionPath = actionPath;
	}

	public boolean isPureJSONRequestMode() {
		return this.mode == MODE_PURE_JSON;
	}

	public int getType() {
		return type;
	}

	protected void setType(int type) {
		this.type = type;
	}

	protected void setTypeAndAction(int type, String actionPath) {
		this.type = type;
		this.actionPath = actionPath;

	}

	public int getMethod() {
		return method;
	}

	protected void setMethod(int method) {
		this.method = method;
	}

	protected void setMode(int mode) {
		this.mode = mode;
	}

	public static Pair p(String name, String value) {
		return new Pair(name, value);
	}

	public static Pair p(String name, int value) {
		return p(name, String.valueOf(value));
	}

	public static Pair p(String name, boolean value) {
		return p(name, String.valueOf(value));
	}

	// used in log...
	public String descName() {
		String name = this.getClass().getName();
		int dot = name.lastIndexOf('.');
		if (dot != -1) {
			return name.substring(dot + 1);
		}
		return name;

	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(" actionPath");
		sb.append(":" + actionPath);
		try {
			sb.append(mode == MODE_KEY_VALUE ? " params:"
					+ Arrays.asList(this.getParams()) : this.getPureJSON()
					.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sb.toString();

	}

}
